package com.whiteblue.model;

import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.ehcache.CacheKit;
import com.whiteblue.config.CFG;
import com.whiteblue.tool.Model;

import java.util.Date;
import java.util.List;

/**
 * Created by WhiteBlue on 15/1/18.
 */
public class Post extends Model<Post> {
    public static final Post dao = new Post();

    public static final String POST_CACHE = "post";
    public static final String POST_LIST_CACHE="post_list";

    public Post() {
        super(POST_CACHE);
    }


    public Page<Post> getPostPage(int pageNumber, int bookID) {
        Page<Post> page = dao.paginateByCache(POST_LIST_CACHE, bookID + "-" + pageNumber, pageNumber, CFG.page_size, "select id", "from b_post where bookId = ?", bookID);
        return loadModelPage(page);
    }

    public void newPost(int bookId,int userId,String content) {
        this.set("bookId", bookId);
        this.set("content", content);
        this.set("time", new Date());
        this.set("userId", userId);
        Book book=Book.dao.getById(bookId);
        book.setRead(bookId);
        this.save();
        removeCache();
    }


    public void deletePost(int Id) {
        dao.deleteById(Id);
        removeCache();
    }

    public void removeCache() {
        CacheKit.removeAll(POST_CACHE);
        CacheKit.removeAll(POST_LIST_CACHE);
    }

    public User getUser() {
        return User.dao.getById(this.getInt("userId"));
    }
}
